$(function(){
	st.searchAjax();
	st.loadChart();
	$('#sc').click(function(e){
		e.preventDefault();
		st.loadChart();
	});
	$('.ajaxitem','.ajaxr').live('mouseover',function(){
		$('.ajaxitem','.ajaxr').removeClass('selected');
		$(this).addClass('selected');
	});	
	$('.ajaxitem','.ajaxr').live('click',function(e){
		e.preventDefault();
		st.selectResult($(this));
	});

    $('#flashgadget').empty().flash({
        src: 'speedtest/speed.swf',
        width: 290,
        height: 125,
        update: true
    });

    $('#submit-test').click(function(e){
        e.preventDefault();
        st.submitResults();
    });
});
var st = {
	searchAjax: function(){
		var s = $('#location');
		var url = 'getlocation.php';
		s.keyup(function(e){
			if(e.keyCode != 40 && e.keyCode !=38 && e.keyCode != 13){
				var k = s.val();
				if(k.length>0){
					setTimeout(function(){ st.findSuggestions(k,s,url) }, 300);
				}else{
					$('body').find('.ajaxr').remove();	
				}
			}
		});
		s.live('keydown',function(e){
			switch(e.keyCode){
				case 40:
					st.resultNav('down');
					return false;
				break;
				case 38:
					st.resultNav('up');
					return false;
				break;
				case 13:
					st.resultNav('enter')
					return false;
				break;
			}
		});
	},
	findSuggestions: function (lastk,elem,url){
		var newk = elem.val();
		if(newk != lastk){
			return
		}
		$.getJSON(url,{'q':newk},function(data){
			if(data){
				st.showResults(data,elem);
			}else{
				$('body').find('.ajaxr').remove();
			}
		});
	},
	showResults: function(data,elem){
		$('body').find('.ajaxr').remove();
		var ar = $('<ul class="ajaxr"></ul>');
		var p = elem.position();
		elem.after(ar);
		ar.css({'top':(p.top+elem.outerHeight()),'left':p.left,'width':elem.outerWidth()});
		$.each(data,function(i,j){
			ar.append('<li class="ajaxitem" rel="'+j.id+'">' +j.name+'</li>');
		});
		ar.children(':first').addClass('selected');
	},
	resultNav: function(direction){
		var ar = $('body').find('.ajaxr');
		var arsize = ar.children('li').size();
		var selectedany = ar.children('.selected').size();
		//log( ar.children('.selected').index());
		var selectedItem =  ar.children('.selected').index();
		switch(direction){
			case "up":
				if(arsize>0 && selectedItem>0){
					selectedItem--;
				}
			break;
			case "down":
				if(arsize>0 && selectedItem<(arsize-1)){					
					selectedItem++;
				}
			break;
			case "enter":
				if(arsize>0 && selectedany!=0){
					st.selectResult(ar.children('li').eq(selectedItem));
				}
				selectedItem = 0;
			break;
		}
		st.selectItem(selectedItem);		
	},
	selectItem: function(si){
		var resultitem = $('body').find('.ajaxr').children('li');
		resultitem.removeClass('selected');
		resultitem.eq(si).addClass('selected');
	},
	selectResult: function(ts){
		var r1 = $(ts).attr('rel');
		var r2 = $(ts).text();
		var results = $('body').find('.ajaxr');
		var elem = results.prev('input');
		results.remove();
		elem.focus().val(r2);
		$('#locid').val(r1);
	},
	drawChart: function(p,l,usrp){
		$.ajax({
			url:'filter.php',
			type:'POST',
			data:{'p':p,'l':l,'usrp':usrp},
			dataType:'json',
			success:function(results){
				
				var chart = new Highcharts.Chart({
					chart: {
						renderTo: 'chart',
						defaultSeriesType: 'area'
					},
					title: {
						text: ' . ' 
					},
					xAxis: {
						type: 'datetime',
						dateTimeLabelFormats: {
							day: '%b %e '
						}
					},
					yAxis: {
						title: {
							text : ''
						},
						labels: {
							formatter: function() {
								return this.value +' Mbps';
							}
						}
					},
					plotOptions: {
						series: {
							stacking: 'normal'
						}
					},
					series: [{
						name: results.dn,
						data: results.d
					},{
						name: 'Your Package',
						data: results.u
					}]
				});	
				console.dir(results.d)
			}
		})
	},
	loadChart: function(){
		var pkg = $('.p','#chart-ctrls').val();
		var loc = $('.l','#chart-ctrls').val();
		var upkg = $('#packageid').val();
		st.drawChart(pkg,loc,upkg);
	},
    saveResults: function(result){
        console.log(result);
        var speed = result[0] / ( result[1] / 1000 );
        console.log('speed', speed, st.nonce);
        st.speed = speed;
    },
    submitResults: function() {
        if (st.speed) {
            $.post("submit.php", { pkgid:"1", locid:"1", down:st.speed, up:0, nonce: st.nonce },
                function (data) {
                    console.log(data);
                    if (data == 'kthx') alert('success!');
                }
            );
        }
    }
};
